package pl.edu.agh.inpema.core.configuration;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.xml.sax.SAXException;

import pl.edu.agh.inpema.core.model.Analyzer;
import pl.edu.agh.inpema.core.model.GlobalResultsSerializer;
import pl.edu.agh.inpema.core.model.Receiver;
import pl.edu.agh.inpema.core.model.globalAnalyzer.GlobalAnalyzer;

public class Configuration {

	//private SAXHandler handler = null;
	private ApplicationContext appContext;
	
	public void readStringXMLConfiguration(String conf) throws IOException, SAXException {
		File tmpFile = File.createTempFile("inpanema_", "_XML");
		Writer writer = new FileWriter(tmpFile);
		writer.write(conf);
		writer.flush();
		this.readXMLFileConfiguration(tmpFile.getAbsolutePath());
	}
	
	public void readXMLFileConfiguration(String fileName) throws IOException, SAXException {
		this.appContext = new FileSystemXmlApplicationContext(fileName);
	}
	
	public Set<Receiver> getReceivers() throws ConfigurationException {
		Set<Receiver> resultSet = new HashSet<Receiver>();
		Map m = this.appContext.getBeansOfType(Receiver.class);
		for (Object o : m.keySet()) {
			Receiver r = (Receiver) m.get(o);
			resultSet.add(r);
		}
		return resultSet;
	}
	
	public Set<Analyzer> getAnalyzers() throws ConfigurationException {
		Set<Analyzer> resultSet = new HashSet<Analyzer>();
		Map m = this.appContext.getBeansOfType(Analyzer.class);
		for (Object o : m.keySet()) {
			Analyzer a = (Analyzer) m.get(o);
			resultSet.add(a);
		}
		return resultSet;
	}
	
	public GlobalAnalyzer getGlobalAnalyzer() throws ConfigurationException {
		Map m = this.appContext.getBeansOfType(GlobalAnalyzer.class);
		if (m.keySet().size() == 0)
			throw new ConfigurationException("no global analyzer in configuration file");
		if (m.keySet().size() > 1)
			throw new ConfigurationException("more than one global analyzer in configuration file");
		GlobalAnalyzer globalAnalyzer = null;
		for (Object o : m.keySet()) {
			globalAnalyzer = (GlobalAnalyzer) m.get(o);
		}
		return globalAnalyzer;
	}
	
	public Set<GlobalResultsSerializer> getGlobalResultSerializers() throws ConfigurationException {
		Set<GlobalResultsSerializer> resultSet = new HashSet<GlobalResultsSerializer>();
		Map m = this.appContext.getBeansOfType(GlobalResultsSerializer.class);
		for (Object o : m.keySet()) {
			GlobalResultsSerializer s = (GlobalResultsSerializer) m.get(o);
			resultSet.add(s);
		}
		return resultSet;
	}
	
}
